import api from '@/api/request/apiConfig'
import axios from 'axios'
import { downloadByStream, getFileNameFormHeader } from './util'
const CancelToken = axios.CancelToken
export class DownloadFile {
  constructor ({ type, apiName, url, params = {}, data, config = {}, headers = {} }) {
    this.type = type
    this.path = apiName ? api[apiName] + url : url
    this.data = data
    config.headers = Object.assign({}, { 'Content-Type': 'application/octet-stream;charset=UTF-8' }, config.headers, headers)
    config.responseType = 'blob'
    config.timeout = 0
    config.params = params
    this.cancel = () => {} // noop
    this.abort = this.abort.bind(this) // 显示的绑定
    const _this = this
    config.cancelToken = new CancelToken(function (c) {
      _this.cancel = c
    })
    this.config = config
  }

  send () {
    return new Promise((resolve, reject) => {
      // put,post第二个参数为data
      const params2 = ['put', 'post'].includes(this.type) ? this.data : this.config
      axios[this.type](this.path, params2, this.config).then(res => {
        const filenameISO = getFileNameFormHeader(res.headers['content-disposition']) // iso-8859-1
        const filename = decodeURI(escape(filenameISO))
        downloadByStream(res.data, filename)
        resolve()
      }).catch(err => {
        console.log(err)
        reject(err)
      })
    })
  }

  abort () {
    this.cancel('已取消下载')
  }
}
